package com.bootdo.app.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bootdo.app.common.msg.Response;
import com.bootdo.app.common.utils.*;
import com.bootdo.app.dao.WXUserMapper;
import com.bootdo.app.util.WxPayUtils;
import com.bootdo.common.utils.HttpUtil;
import com.bootdo.common.utils.MD5Utils;
import com.bootdo.common.utils.R;
import com.bootdo.system.dao.DyPayDao;
import com.bootdo.system.dao.UserDao;
import com.bootdo.system.domain.*;
import com.bootdo.system.dto.DyPayDto;
import com.bootdo.system.service.UserLsService;
import com.bootdo.system.service.WxConfigService;
import com.bootdo.system.service.WxUserService;
import com.google.gson.JsonObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @create 2021-02-28 16-48
 */
@Api(description = "电影接口")
@RestController
@RequestMapping("/app/dy")
public class DyController {
    private static final String BASE_URL = "https://service-g8f5yslp-1303204763.sh.apigw.tencentcs.com";
    private static final String AGENT_ID = "agent_id100034";
    private static final String SECERT = "88b57fddb473aad644ef4b807678a16a";
    @Autowired
    private DyPayDao dyPayDao;

    @Autowired
    private WxConfigService wxConfigService;
    @Autowired
    private WxUserService wxUserService;

    @ApiOperation("加密")
    @PostMapping("/sigin")
    public String createSiginId(Map map) throws Exception {
        String dySigin = MD5Utils.createDySigin(new JSONObject().fluentPutAll(map));

        return dySigin;
    }

    public static void main(String[] args) throws Exception {
        JSONObject jsonObject = JSON.parseObject("{\"showId\":\"NzMyNjEjQGltYW5tQCMxMjMyNzQjQGltYW5tQCMxNjE0NjA3MjAwI0BpbWFubUAjNzgjQGltYW5tQCM2MQ==\", \"signid\":\"1c32a1ee6bfc2f5e5d5e8ceed324ffaf\", \"agent_id\":\"100034\"}");
        String dySigin = MD5Utils.createDySigin(jsonObject);
        System.out.println(dySigin);
        //createDyOrder();
    }

    @PostMapping("/cratePay")
    public  Response createDyOrder(@RequestBody DyPayDto payDto, HttpServletRequest request) throws Exception {
        String payPrice = "30";


        String currentUserId = ContextHandlerUtil.getCurrentUserId();
        String openId = ContextHandlerUtil.getOpenId();
        String sid = ContextHandlerUtil.getSID();
        TbWeixinconfig tbWeixinconfig = wxConfigService.selectByUserId(Integer.valueOf(sid));
        if(tbWeixinconfig == null){
            System.out.println("微信配置信息获取失败!");
            return Response.fail("支付失败");
        }


        String applicationPostUrl = BASE_URL + "/api/order/third/submit";

        String orderPay = BASE_URL+"/api/order/buy/pay";

        Map pyMap = new HashMap();
        //map.put("tel","17638599615");
        //map.put("room_id","NzMyNjEjQGltYW5tQCMxMjMyNzQjQGltYW5tQCMxNjE0NjA3MjAwI0BpbWFubUAjNzgjQGltYW5tQCM2MQ==");
        //array.add("NzMyNjFAX0AxMjMyNzRAX0AxNjE0NjA3MjAwQF9ANzhAX0A2MUBfQDAwMDAwMDAwMDEjMSMwIzFAX0A2MUBfQDBAX0A45o6SMeW6pw");
        //map.put("cinema_id","73261");
        //map.put("film_id","123274");
          /* JSONObject jsonObject1 = JSON.parseObject("   {\n" +
                "                    \"ColumnNum\": \"17\",\n" +
                "                    \"RowNum\": \"8\",\n" +
                "                    \"seatNo\": \"8排1座\",\n" +
                "                    \"seatNo\": \"N\",\n" +
                "                    \"lovestatus\": 0,\n" +
                "                    \"SeatCode\": \"NzMyNjFAX0AxMjMyNzRAX0AxNjE0NjA3MjAwQF9ANzhAX0A2MUBfQDAwMDAwMDAwMDEjMSMwIzFAX0A2MUBfQDBAX0A45o6SMeW6pw==\"\n" +
                "                }");*/
        pyMap.put("tel",payDto.getTel());
        pyMap.put("room_id",payDto.getRoom_id());
        JSONArray array = new JSONArray();
        array.addAll(payDto.getSeat_id());

        pyMap.put("seat_id",array.toString());

        pyMap.put("cinema_id",payDto.getCinema_id());

        pyMap.put("film_id",payDto.getFilm_id());

        JSONArray array1 = new JSONArray();
        array1.addAll(payDto.getSeat_data());
        pyMap.put("seat_data",array1.toString());
        pyMap.put("attach","");
        pyMap.put("agent_id","100034");
        JSONObject jsonObject = new JSONObject();
        jsonObject.fluentPutAll(pyMap);
        String dySigin = MD5Utils.createDySigin(jsonObject);
        pyMap.put("signid",dySigin);
        System.out.println(new JSONObject(pyMap).toString());
        String s = HttpUtil.doPost(applicationPostUrl, pyMap, null);
        JSONObject creadOrder = JSONObject.parseObject(s);

        if(creadOrder.getString("code").equals("000")){
            JSONObject date = creadOrder.getJSONObject("data");
            JSONObject order_info = date.getJSONObject("order_info");
            String orderNum = order_info.getString("order_number");

            Map orderMap = new HashMap();
            orderMap.put("order_number",orderNum);
            orderMap.put("agent_id","100034");
            String orderSign = MD5Utils.createDySigin(orderMap);
            orderMap.put("signid",orderSign);
            //下单扣款
            String s1 = HttpUtil.doPost(orderPay, orderMap, null);
            JSONObject buyPay = JSON.parseObject(s1);
            if("000".equals(buyPay.get("code"))){
                String spbill_create_ip = WXPay.getIpAddr(request);
                String appId = payDto.getAppId();
                String nonce_str = WXPay.getRandomStringByLength(32);
                Map response = WxPayUtils.createWxPayXml(appId, payDto.getDyName(), spbill_create_ip, payPrice, orderNum, openId,nonce_str);


                TbDyPay dyPay = new TbDyPay();
                dyPay.setOrderNum(order_info.getString("order_number"));
                dyPay.setDyName("");
                dyPay.setUserId(Long.valueOf(currentUserId));
                dyPay.setPayPrice(date.getBigDecimal("final_price"));
                dyPay.setPrice(date.getBigDecimal("maoyan_price"));
                dyPay.setCreateTime(LocalDateTime.now().toString());
                dyPayDao.insertPayDao(dyPay);
                //System.out.println(dyPay);
                return Response.success(response);
            }
            System.out.println(s1);
        }
        return Response.fail("支付失败");
    }


    @PostMapping("/notify")
    public JSONObject dyNotify(@RequestBody JSONObject jsonObject){
        JSONObject jsonObject1 = new JSONObject();
        Map orderMap = new HashMap();
        String thirdUrl = BASE_URL+"/api/order/third/info";
        String order_number = jsonObject.getString("order_number");
        try {
            orderMap.put("order_number",order_number);
            orderMap.put("agent_id","100034");
            JSONObject md5Json = new JSONObject();
            md5Json.fluentPutAll(orderMap);
            String dySigin = MD5Utils.createDySigin(md5Json);
            orderMap.put("signid",dySigin);
            System.out.println(new JSONObject(orderMap).toString());
            String s = HttpUtil.doPost(thirdUrl, orderMap, null);
            JSONObject orderResult = JSON.parseObject(s);


            TbDyPay dyPay = new TbDyPay();
            String code = jsonObject.getString("code");
            String ordrNo = jsonObject.getString("order_number");

            BigDecimal bigDecimal = jsonObject.getBigDecimal("rebate");
            dyPay.setPayState(orderResult.getInteger("pay_state"));
            dyPay.setHandleStrp(orderResult.getInteger("handle_step"));
            dyPay.setOrderNum(ordrNo);

            dyPayDao.updateByordreNo(dyPay);
            profit(order_number);
            jsonObject1.put("code","1");
        }catch (Exception e){
            jsonObject1.put("code","0");
        }

        return jsonObject1;
    }

    @Autowired
    private UserDao userDao;
    @Autowired
    private UserLsService userLsService;

    private void profit(String order_number){
        TbDyPay dyPay = dyPayDao.selectByOrderNo(order_number);
        Long userId = dyPay.getUserId();
        TbWxuser byId = wxUserService.getById(userId.intValue());
        String sid = byId.getSid();
        TbWeixinconfig tbWeixinconfig = wxConfigService.selectByUserId(Integer.valueOf(sid));

        UserDO userDO = userDao.get(Long.valueOf(sid));
        Integer dyScale = userDO.getDyScale();

        BigDecimal payPrice = dyPay.getPayPrice();
        BigDecimal price = dyPay.getPrice();
        BigDecimal subtract = payPrice.subtract(price);

        //代理分润
        BigDecimal multiply = subtract.multiply(BigDecimal.valueOf(dyScale / 100));
        Double userProfit = getDouble2String(multiply.toString());

        //一级分润
        String balance = byId.getBalance();
        BigDecimal multiply2 = multiply.multiply(BigDecimal.valueOf(tbWeixinconfig.getLevelone() / 100));
        Double double2String = getDouble2String(balance);
        Double double2String1 = getDouble2String(multiply2.toString());
        userProfit = userProfit - double2String1;
        byId.setBalance(String.valueOf(double2String+double2String1));
        wxUserService.insert2update(byId);

        TbJcLog tbJcLog = new TbJcLog();
        tbJcLog.setWxId(byId.getId());
        tbJcLog.setJcje(new BigDecimal(double2String1));
        tbJcLog.setUserId(Integer.valueOf(sid));
        tbJcLog.setJczt(1);
        tbJcLog.setJcbz("电影一级返佣");
        wxUserService.insertJc(tbJcLog);
        //二级分润
        Integer wxuserId = byId.getWxuserId();
        if(wxuserId != 0){
            BigDecimal multiply1 = multiply.multiply(BigDecimal.valueOf(tbWeixinconfig.getLeveltwo() / 100));
            TbWxuser byId1 = wxUserService.getById(wxuserId);
            Double double2String2 = getDouble2String(byId1.getBalance());
            double v = multiply1.doubleValue();
            userProfit = userProfit - v;
            byId1.setBalance(String.valueOf(double2String2+v));
            wxUserService.insert2update(byId1);

            TbJcLog tbJcLog2 = new TbJcLog();
            tbJcLog2.setWxId(byId1.getId());
            tbJcLog2.setJcje(multiply1);
            tbJcLog2.setUserId(Integer.valueOf(sid));
            tbJcLog2.setJczt(1);
            tbJcLog2.setJcbz("电影二级返佣");
            wxUserService.insertJc(tbJcLog);



            Integer wxuserSubId = byId.getWxuserId();
            if(wxuserSubId != 0){
                BigDecimal multiply3 = multiply.multiply(BigDecimal.valueOf(tbWeixinconfig.getLevelthree() / 100));
                TbWxuser byId2 = wxUserService.getById(wxuserSubId);
                Double double2String3 = getDouble2String(byId2.getBalance());
                double v1 = multiply3.doubleValue();
                userProfit = userProfit - v1;
                byId2.setBalance(String.valueOf(double2String3+v1));
                wxUserService.insert2update(byId2);

                TbJcLog tbJcLog3 = new TbJcLog();
                tbJcLog3.setWxId(byId2.getId());
                tbJcLog3.setJcje(multiply3);
                tbJcLog3.setUserId(Integer.valueOf(sid));
                tbJcLog3.setJczt(1);
                tbJcLog3.setJcbz("电影三级返佣");
                wxUserService.insertJc(tbJcLog);

            }
        }


        Double userbalane = getDouble2String(userDO.getBalance());
        userDO.setBalance(String.valueOf(userbalane+userProfit));
        userDao.update(userDO);

        TbUserWater tbUserWater = new TbUserWater();
        //用户下单类型
        tbUserWater.setZjlx(6);
        tbUserWater.setWaterJe(multiply+"");
        tbUserWater.setUserId(Long.valueOf(sid));
        tbUserWater.setOrderId(String.valueOf(dyPay.getId()));
        tbUserWater.setOrderType(5);
        userLsService.insert(tbUserWater);

    }


    private Double getDouble2String(String num) {
        if(StringUtils.isNoneBlank(num)) {
            Double cny = Double.parseDouble(num);
            DecimalFormat df = new DecimalFormat("0.00000");
            String CNY = df.format(cny);
            Double cny1 = Double.parseDouble(CNY);
            return cny1;
        }
        return 0.00;
    }
}
